$(function() {
	var actionError = $("#actionError").val();
	if ($.trim(actionError) != '') {
		var arrayError = eval("(" + actionError + ")");
		if (arrayError != null) {
			var fieldName = arrayError.fieldName;
			if ($.trim(fieldName) == '') {
				showMessageBox(arrayError);
			} else {
				showMessageTip(arrayError);
			}
		}
	}

	$(document).bind('touchstart', function() {
	});
	
	$(document).on('mouseenter', '[data-title]', function () {
		var $this = $(this);
		var msg = $this.attr("data-title");
		var place = "top";
		if ($this.attr("data-place")) {
			place = $this.attr("data-place");
		}
		showTooltip(msg, $this, place);
	});
	
	$(document).on('click', '.dropdown>ul>li>a', function () {
		var $this = $(this);
		var $li = $this.parent();
		if (!$li.hasClass("disabled") && !$li.hasClass("active")) {
			var text = $this.text();
			var value = $this.attr("data-value");
			var li = $this.parent();
			var dropdown = li.parent().parent();
			dropdown.children("input").val(value).change();
			dropdown.children("button").children(".text").text(text);
			li.addClass("active").siblings().removeClass("active");
		}
	});
	
	$(document).on('setVal', '.dropdown', function (e, val) {
		var dropdown = $(this);
		dropdown.find("ul>li>a").each(function() {
			var dataValue = $(this).attr("data-value");
			if (dataValue == val) {
				$(this).click();
				return;
			}
		});
	});
	
	$(document).on('click', '.form-calendar .btn:not(.disabled)', function () {
		var $this = $(this);
		var $calendar = $this.parent().parent();
		$calendar.children(".form-control").click();
	});
	
	$(document).on('change', '.tab-btn-menu input', function () {
		var $this = $(this);
		var $label = $this.parent();
		var currentActiveOffsetLeft = $label.position().left;
		var slideLineMove = $label.parent().parent().children(".slide-line");
		slideLineMove.animate({
			"left": currentActiveOffsetLeft
		}, 300, 'easeOutQuad');
	});
});

function showErrorMessageBox(msg) {
	var actionError = '{"fieldName":"","message":"' + msg + '","messageDiv":"01"}';
	var arrayError = eval("(" + actionError + ")");
	if ($('#messageBox').length > 0) {
		$('#messageBox').modal('hide');
		setTimeout(function() {
			showMessageBox(arrayError);
		}, 400);
	} else {
		showMessageBox(arrayError);
	}
}

function showInfoMessageBox(msg) {
	var actionError = '{"fieldName":"","message":"' + msg + '","messageDiv":"02"}';
	var arrayError = eval("(" + actionError + ")");
	if ($('#messageBox').length > 0) {
		$('#messageBox').modal('hide');
		setTimeout(function() {
			showMessageBox(arrayError);
		}, 400);
	} else {
		showMessageBox(arrayError);
	}
}

function showMessageBox(arrayError) {
	var messageBoxHtml = '<div class="modal fade" id="messageBox">';
	messageBoxHtml += '<div class="modal-dialog">';
	messageBoxHtml += '<div class="modal-content">';
	messageBoxHtml += '<div class="modal-body">';
	messageBoxHtml += '<ul>';
	if ($.trim(arrayError.message) != '') {
		if (arrayError.messageDiv == '01') {
			messageBoxHtml += '<li class="error">' + arrayError.message + "</li>";
		} else if (arrayError.messageDiv == '02') {
			messageBoxHtml += '<li class="info">' + arrayError.message + "</li>";
		}
	}
	messageBoxHtml += '</ul>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '<div class="modal-footer">';
	messageBoxHtml += '<button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	messageBoxHtml += '</div>';
	$("body").append(messageBoxHtml);
	$('#messageBox').modal('show');
	$('#messageBox').on('hidden.bs.modal', function(e) {
		$(this).remove();
	});
}

function showErrorMessageTip(msg, field, fieldIdx) {
	var actionError = '{"fieldName":"' + field + '","message":"' + msg + '","messageDiv":"01"}';
	var arrayError = eval("(" + actionError + ")");
	showMessageTip(arrayError, fieldIdx);
}

function showMessageTip(arrayError, fieldIdx) {
	var fieldName = arrayError.fieldName;
	var field;
	if (!isNaN(parseInt(fieldIdx))) {
		field = $("[name='" + fieldName + "']:eq(" + fieldIdx + ")");
	} else {
		field = $("[name='" + fieldName + "']");
	}
	var msg = arrayError.message;
	var place = "top";
	showTooltip(msg, field, place);
}

function showTooltip(msg, field, place) {
	field.removeAttr("data-toggle").attr("data-toggle", "tooltip");
	field.removeAttr("data-placement").attr("data-placement", place);
	field.removeAttr("data-original-title").attr("data-original-title", msg);
	field.tooltip("show");
	field.focus();
	field.on('hidden.bs.tooltip', function() {
		field.tooltip('dispose');
		field.removeAttr("data-toggle");
		field.removeAttr("data-placement");
		field.removeAttr("data-original-title");
	});
}

function showAlertBox(message) {
	if ($("#alertBox").length > 0) {
		$("#alertBox").alert('close');
	}
	var html = '<div id="alertBox" style="opacity: 0;"><div class="alert alert-info" role="alert">';
	html += message;
	html += '</div></div>';
	$("#wrapper").append(html);
	var alertBox = $("#alertBox");
	alertBox.animate({
		"opacity": 1
	}, 500, 'easeOutQuad', function() {
		setTimeout(function() {
			alertBox.animate({
				"opacity": 0
			}, 1500, 'easeOutQuad', function() {
				$("#alertBox").remove();
			});
		}, 500);
	});
}

/**
 * 时间对象的格式化;
 */
Date.prototype.format = function(format) {
	/*
	 * 使用例子:format="yyyy-MM-dd hh:mm:ss";
	 */
	var o = {
		"M+": this.getMonth() + 1, // month
		"d+": this.getDate(), // day
		"h+": this.getHours(), // hour
		"H+": this.getHours(), // hour
		"m+": this.getMinutes(), // minute
		"s+": this.getSeconds(), // second
		"q+": Math.floor((this.getMonth() + 3) / 3), // quarter
		"S": this.getMilliseconds()
		// millisecond
	}
	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}

function calcDateByDay(date, fmt, days) {
	date.setDate(date.getDate() + days);
	return date.format(fmt);
}

function toDate(date) {
	return new Date(date.replace(/\-/g, "/"));
}

//form序列化为json
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

//获取url后的参数值
function getUrlParam(key) {
	var href = window.location.href;
	var url = href.split("?");
	if(url.length <= 1){
		return "";
	}
	var params = url[1].split("&");
	
	for(var i=0; i<params.length; i++){
		var param = params[i].split("=");
		if(key == param[0]){
			return param[1];
		}
	}
}

// 检查登录状态
function loginInfo(){
	var user = "";
    $.ajax({
        type : 'get',
        url : '/sys/login',
        async: false,
        success : function(data){
            if(data != null && data != ""){
                user = data;
            }
        },
        error: function(xhr,textStatus,errorThrown){
            var msg = xhr.responseText;
            var response = JSON.parse(msg);
            $("#info").html(response.message);
        }
    });
    
    return user;
}

function maxPic(path) {
    $("#maxPic").attr("src",path);
    $("#picMonthDialog").modal("toggle");
}

$(document).ready(function() {
    layui.use('layer', function(){
        var layer = layui.layer;
    });
});

